package com.cdxy.service.impl;

import com.cdxy.enums.BizErrorEnum;
import com.cdxy.enums.redis.RedisCacheGroupEnum;
import com.cdxy.model.dto.base.exception.BusinessException;
import com.cdxy.model.dto.base.redis.RedisCacheManager;
import com.cdxy.model.dto.resp.ImgCodeResp;
import com.cdxy.service.IImgService;
import com.cdxy.util.IdUtil;
import com.wf.captcha.ArithmeticCaptcha;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @Author: tangy
 * @Date: 2020/2/23 19:43
 */
@Service
@Slf4j
public class ImgServiceImpl implements IImgService {

    @Value("${login.expiration:2}")
    private int expiration;

    private RedisCacheManager redisCacheManager;

    public ImgServiceImpl(RedisCacheManager redisCacheManager) {
        this.redisCacheManager = redisCacheManager;
    }

    @Override
    public ImgCodeResp getImgCode(RedisCacheGroupEnum redisCacheGroupEnum) {
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(111, 36);
        // 几位数运算，默认是两位
        captcha.setLen(2);
        // 获取运算的结果
        String result = captcha.text();
        String uuid = "code-key" + IdUtil.simpleUUID();
        // 保存
        log.info("验证码是" + result);
        redisCacheManager.put(redisCacheGroupEnum, uuid, result, (expiration * 60));

        ImgCodeResp imgCodeResp = new ImgCodeResp();
        imgCodeResp.setImg(captcha.toBase64());
        imgCodeResp.setUuid(uuid);
        return imgCodeResp;
    }

    @Override
    public void checkImgCode(RedisCacheGroupEnum redisCacheGroupEnum, String uuid, String code) {
        String cacheCode = (String) redisCacheManager.get(redisCacheGroupEnum, uuid);
        redisCacheManager.delete(redisCacheGroupEnum, uuid);
        if (StringUtils.isBlank(cacheCode)) {
            throw new BusinessException(BizErrorEnum.VERIFICATION_CODE_ERROR, "验证码不存在或已过期");
        }
        if (StringUtils.isBlank(code) || !code.equalsIgnoreCase(cacheCode)) {
            throw new BusinessException(BizErrorEnum.VERIFICATION_CODE_ERROR, "验证码错误");
        }
    }

}
